<template>
  <PageContainer title="用户管理">
    <!-- 搜索筛选区域 -->
    <SearchForm v-model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-form-item label="用户筛选">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入用户名或手机号"
          clearable
        />
      </el-form-item>
      <el-form-item label="用户状态">
        <el-select
          v-model="searchForm.status"
          placeholder="请选择用户状态"
          clearable
        >
          <el-option label="正常" value="active" />
          <el-option label="禁用" value="disabled" />
          <el-option label="待审核" value="pending" />
        </el-select>
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="用户等级">
        <el-select
          v-model="searchForm.level"
          placeholder="请选择用户等级"
          clearable
        >
          <el-option label="普通用户" value="normal" />
          <el-option label="VIP用户" value="vip" />
          <el-option label="企业用户" value="enterprise" />
        </el-select>
      </el-form-item>
    </SearchForm>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <StatCard
        :icon="User"
        icon-bg="#409EFF"
        :value="userStats.totalCount"
        label="总用户数"
        :trend="userStats.totalTrend"
      />
      <StatCard
        :icon="UserFilled"
        icon-bg="#67C23A"
        :value="userStats.activeCount"
        label="活跃用户"
        :trend="userStats.activeTrend"
      />
      <StatCard
        :icon="Calendar"
        icon-bg="#E6A23C"
        :value="userStats.todayRegister"
        label="今日注册"
        :trend="userStats.registerTrend"
      />
      <StatCard
        :icon="Money"
        icon-bg="#F56C6C"
        :value="`¥${userStats.totalBalance}`"
        label="用户总余额"
        :trend="userStats.balanceTrend"
      />
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button
          type="primary"
          @click="handleAddUser"
        >
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        <el-button
          type="success"
          :disabled="!selectedRows.length"
          @click="handleBatchEnable"
        >
          <el-icon><Check /></el-icon>
          批量启用
        </el-button>
        <el-button
          type="warning"
          :disabled="!selectedRows.length"
          @click="handleBatchDisable"
        >
          <el-icon><Close /></el-icon>
          批量禁用
        </el-button>
        <el-button
          type="info"
          @click="handleExport"
        >
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
      <div class="action-right">
        <el-button
          type="info"
          @click="loadUserList"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <DataTable
      :data="userList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="用户ID" width="80" />
      <el-table-column prop="name" label="用户名" width="120" />
      <el-table-column prop="phone" label="注册号码" width="140" />
      <el-table-column label="用户等级" width="100">
        <template #default="{ row }">
          <el-tag :type="getLevelTag(row.level)">
            {{ getLevelText(row.level) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="账户余额" width="120" sortable>
        <template #default="{ row }">
          <span class="balance-text">¥{{ row.balance }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投递次数" width="100" sortable>
        <template #default="{ row }">
          {{ row.disposalCount }}
        </template>
      </el-table-column>
      <el-table-column label="累计收益" width="120" sortable>
        <template #default="{ row }">
          <span class="earnings-text">¥{{ row.totalEarnings }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="最后登录" width="180">
        <template #default="{ row }">
          {{ row.lastLoginAt ? formatDateTime(row.lastLoginAt) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="用户状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command: string) => handleMoreAction(command, row)">
            <el-button type="text" size="small">
              更多<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  :command="row.status === 'active' ? 'disable' : 'enable'"
                >
                  {{ row.status === 'active' ? '禁用' : '启用' }}
                </el-dropdown-item>
                <el-dropdown-item command="balance">余额管理</el-dropdown-item>
                <el-dropdown-item command="disposal">投递记录</el-dropdown-item>
                <el-dropdown-item command="reset-password">重置密码</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="70%"
    >
      <div v-if="currentUser" class="user-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="用户ID">
                {{ currentUser.id }}
              </el-descriptions-item>
              <el-descriptions-item label="用户名">
                {{ currentUser.name }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                {{ currentUser.phone }}
              </el-descriptions-item>
              <el-descriptions-item label="用户等级">
                <el-tag :type="getLevelTag(currentUser.level)">
                  {{ getLevelText(currentUser.level) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="用户状态">
                <el-tag :type="getStatusTag(currentUser.status)">
                  {{ getStatusText(currentUser.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="注册时间">
                {{ formatDateTime(currentUser.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="最后登录">
                {{ currentUser.lastLoginAt ? formatDateTime(currentUser.lastLoginAt) : '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions title="账户信息" :column="1" border>
              <el-descriptions-item label="账户余额">
                <span class="balance-text">¥{{ currentUser.balance }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="累计收益">
                <span class="earnings-text">¥{{ currentUser.totalEarnings }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="投递次数">
                {{ currentUser.disposalCount }}
              </el-descriptions-item>
              <el-descriptions-item label="成功投递">
                {{ currentUser.successfulDisposals }}
              </el-descriptions-item>
              <el-descriptions-item label="异常投递">
                {{ currentUser.exceptionDisposals }}
              </el-descriptions-item>
              <el-descriptions-item label="投递成功率">
                {{ currentUser.successRate }}%
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>

        <!-- 最近投递记录 -->
        <div class="recent-disposals" style="margin-top: 20px;">
          <h4>最近投递记录</h4>
          <el-table :data="currentUser.recentDisposals" size="small">
            <el-table-column prop="id" label="记录ID" width="100" />
            <el-table-column prop="deviceName" label="设备名称" width="150" />
            <el-table-column prop="wasteType" label="垃圾类型" width="100" />
            <el-table-column prop="weight" label="重量(kg)" width="100" />
            <el-table-column prop="earnings" label="收益" width="100">
              <template #default="{ row }">
                ¥{{ row.earnings }}
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="投递时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'success' ? 'success' : 'warning'">
                  {{ row.status === 'success' ? '成功' : '异常' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model="userForm.name"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="userForm.phone"
            placeholder="请输入手机号"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="用户等级" prop="level">
          <el-select
            v-model="userForm.level"
            placeholder="请选择用户等级"
          >
            <el-option label="普通用户" value="normal" />
            <el-option label="VIP用户" value="vip" />
            <el-option label="企业用户" value="enterprise" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-select
            v-model="userForm.status"
            placeholder="请选择用户状态"
          >
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
            <el-option label="待审核" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="初始余额" prop="balance">
          <el-input-number
            v-model="userForm.balance"
            :min="0"
            :precision="2"
            placeholder="请输入初始余额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 余额管理对话框 -->
    <el-dialog
      v-model="balanceDialogVisible"
      title="余额管理"
      width="500px"
    >
      <el-form
        ref="balanceFormRef"
        :model="balanceForm"
        :rules="balanceRules"
        label-width="100px"
      >
        <el-form-item label="当前余额">
          <span class="balance-text">¥{{ currentUser?.balance || 0 }}</span>
        </el-form-item>
        <el-form-item label="操作类型" prop="type">
          <el-radio-group v-model="balanceForm.type">
            <el-radio label="add">充值</el-radio>
            <el-radio label="deduct">扣除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="balanceForm.amount"
            :min="0.01"
            :precision="2"
            placeholder="请输入金额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="操作原因" prop="reason">
          <el-input
            v-model="balanceForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入操作原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="balanceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBalanceSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  User,
  UserFilled,
  Calendar,
  Money,
  Plus,
  Check,
  Close,
  Download,
  Refresh,
  ArrowDown
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import SearchForm from '@/components/SearchForm.vue'
import DataTable from '@/components/DataTable.vue'
import StatCard from '@/components/StatCard.vue'
import { useUserStore } from '@/stores/user'
import { formatDateTime } from '@/utils'

const userStore = useUserStore()

const loading = ref(false)
const submitting = ref(false)
const detailDialogVisible = ref(false)
const userDialogVisible = ref(false)
const balanceDialogVisible = ref(false)
const isEdit = ref(false)
const currentUser = ref<any>(null)
const selectedRows = ref<any[]>([])
const userFormRef = ref<FormInstance>()
const balanceFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  level: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 用户统计
const userStats = reactive({
  totalCount: 12580,
  totalTrend: '+8.5%',
  activeCount: 9876,
  activeTrend: '+12.3%',
  todayRegister: 45,
  registerTrend: '+25.6%',
  totalBalance: '156,789.50',
  balanceTrend: '+5.2%'
})

// 用户列表
const userList = ref<any[]>([])

// 用户表单
const userForm = reactive({
  name: '',
  phone: '',
  password: '',
  level: 'normal',
  status: 'active',
  balance: 0,
  remark: ''
})

// 余额表单
const balanceForm = reactive({
  type: 'add',
  amount: null,
  reason: ''
})

// 表单验证规则
const userRules: FormRules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择用户等级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ]
}

const balanceRules: FormRules = {
  type: [
    { required: true, message: '请选择操作类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入操作原因', trigger: 'blur' },
    { min: 5, max: 200, message: '原因长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取等级标签
const getLevelTag = (level: string) => {
  switch (level) {
    case 'vip':
      return 'warning'
    case 'enterprise':
      return 'success'
    default:
      return 'info'
  }
}

// 获取等级文本
const getLevelText = (level: string) => {
  switch (level) {
    case 'normal':
      return '普通用户'
    case 'vip':
      return 'VIP用户'
    case 'enterprise':
      return '企业用户'
    default:
      return '未知'
  }
}

// 获取状态标签
const getStatusTag = (status: string) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'disabled':
      return 'danger'
    case 'pending':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'active':
      return '正常'
    case 'disabled':
      return '禁用'
    case 'pending':
      return '待审核'
    default:
      return '未知'
  }
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    const response = await userStore.fetchUserList(params)
    userList.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadUserList()
}

// 重置处理
const handleReset = () => {
  pagination.page = 1
  loadUserList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadUserList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadUserList()
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 新增用户
const handleAddUser = () => {
  isEdit.value = false
  Object.assign(userForm, {
    name: '',
    phone: '',
    password: '',
    level: 'normal',
    status: 'active',
    balance: 0,
    remark: ''
  })
  userDialogVisible.value = true
}

// 编辑用户
const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(userForm, row)
  userDialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row: any) => {
  // 模拟获取用户详细信息
  currentUser.value = {
    ...row,
    successfulDisposals: 156,
    exceptionDisposals: 12,
    successRate: 92.8,
    recentDisposals: [
      {
        id: 1001,
        deviceName: '智能回收箱A01',
        wasteType: '塑料',
        weight: 2.5,
        earnings: 5.20,
        createdAt: '2024-01-15 14:30:00',
        status: 'success'
      },
      {
        id: 1002,
        deviceName: '智能回收箱B02',
        wasteType: '纸类',
        weight: 1.8,
        earnings: 3.60,
        createdAt: '2024-01-14 16:20:00',
        status: 'success'
      }
    ]
  }
  detailDialogVisible.value = true
}

// 用户表单提交
const handleUserSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    submitting.value = true
    
    // 调用创建/更新用户API
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    userDialogVisible.value = false
    loadUserList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

// 余额管理
const handleBalanceManagement = (row: any) => {
  currentUser.value = row
  Object.assign(balanceForm, {
    type: 'add',
    amount: null,
    reason: ''
  })
  balanceDialogVisible.value = true
}

// 余额表单提交
const handleBalanceSubmit = async () => {
  if (!balanceFormRef.value) return
  
  try {
    await balanceFormRef.value.validate()
    submitting.value = true
    
    // 调用余额调整API
    ElMessage.success('余额调整成功')
    balanceDialogVisible.value = false
    loadUserList()
  } catch (error) {
    ElMessage.error('余额调整失败')
  } finally {
    submitting.value = false
  }
}

// 批量启用
const handleBatchEnable = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedRows.value.length} 个用户吗？`,
      '批量启用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用批量启用API
    ElMessage.success('批量启用成功')
    loadUserList()
  } catch (error) {
    // 用户取消
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedRows.value.length} 个用户吗？`,
      '批量禁用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用批量禁用API
    ElMessage.success('批量禁用成功')
    loadUserList()
  } catch (error) {
    // 用户取消
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 更多操作
const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'enable':
    case 'disable':
      // 启用/禁用用户
      ElMessage.info(`${command === 'enable' ? '启用' : '禁用'}用户功能开发中...`)
      break
    case 'balance':
      handleBalanceManagement(row)
      break
    case 'disposal':
      ElMessage.info('投递记录功能开发中...')
      break
    case 'reset-password':
      ElMessage.info('重置密码功能开发中...')
      break
  }
}

onMounted(() => {
  loadUserList()
})
</script>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.balance-text {
  font-weight: 600;
  color: #409eff;
}

.earnings-text {
  font-weight: 600;
  color: #67c23a;
}

.user-detail {
  .recent-disposals {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }
}
</style>